<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" v-loading="formLoading">
      <el-form-item label="上级" prop="pid">
        <el-tree-select v-model="formData.pid" :data="drawingNoBomTree" :props="{ ...defaultProps, label: 'code' }"
          check-strictly default-expand-all placeholder="请选择上级" />
      </el-form-item>

      <el-form-item label="图号Id" prop="drawingNoId" v-if="formType !== 'create'">
        <el-input v-model="formData.drawingNoId" placeholder="请输入图号Id" />
      </el-form-item>

      <el-form-item label="编号" prop="code">
        <el-input v-model="formData.code" placeholder="请输入编号" />
      </el-form-item>

      <el-form-item label="名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入名称" />
      </el-form-item>

      <!-- 新增：模具选择下拉 -->
      <el-form-item label="模具" prop="accountId">
        <el-select v-model="formData.accountId" filterable clearable placeholder="请选择模具" style="width: 100%"
          @change="handleAccountChange">
          <el-option v-for="account in accountList" :key="account.id" :label="account.code + '(' + account.name + ')'"
            :value="account.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="描述/备注" prop="description">
        <Editor v-model="formData.description" height="150px" />
      </el-form-item>

      <el-form-item label="启用状态" prop="status">
        <el-switch v-model="formData.status" :active-value="true" :inactive-value="false" active-text="启用"
          inactive-text="禁用" />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { DrawingNoBomApi, DrawingNoBom } from '@/api/mold/drawingnobom'
import { defaultProps, handleTree } from '@/utils/tree'
import { AccountApi, Account } from '@/api/mold/account'

/** 模具图号BOM 表单 */
defineOptions({ name: 'DrawingNoBomForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  pid: undefined,
  drawingNoId: undefined as number | undefined,
  code: undefined as string | undefined,
  name: undefined as string | undefined,
  accountId: undefined as number | undefined, // 模具ID
  accountCode: undefined as string | undefined, // 明确可为 string
  accountName: undefined as string | undefined, // 明确可为 string
  description: undefined as string | undefined,
  status: true // 默认开启
})

const formRules = reactive({
  drawingNoId: [{ required: true, message: '图号Id不能为空', trigger: 'blur' }],
  pid: [{ required: true, message: '上级不能为空', trigger: 'blur' }],
  code: [{ required: true, message: '编号不能为空', trigger: 'blur' }],
  name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
  accountId: [{ required: true, message: '模具不能为空', trigger: 'blur' }] // 必填校验
})

const formRef = ref() // 表单 Ref
const drawingNoBomTree = ref() // 树形结构
const accountList = ref<Account[]>([]) // 模具列表

/** 打开弹窗 */
const open = async (type: string, id?: number, drawingNoId?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  if (type === 'create' && drawingNoId) {
    formData.value.drawingNoId = drawingNoId
  }

  if (id) {
    formLoading.value = true
    try {
      formData.value = await DrawingNoBomApi.getDrawingNoBom(id)
    } finally {
      formLoading.value = false
    }
  }

  await getAccountList()
  await getDrawingNoBomTree()
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单（新增时跳过图号Id校验）
  if (formType.value !== 'create') {
    await formRef.value.validate()
  } else {
    const fieldsToValidate = ['code', 'name', 'accountId', 'status']
    await formRef.value.validateField(fieldsToValidate)
  }

  formLoading.value = true
  try {
    const data = formData.value as unknown as DrawingNoBom
    if (formType.value === 'create') {
      await DrawingNoBomApi.createDrawingNoBom(data)
      message.success(t('common.createSuccess'))
    } else {
      await DrawingNoBomApi.updateDrawingNoBom(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    pid: undefined,
    drawingNoId: undefined,
    code: undefined,
    name: undefined,
    accountId: undefined,
    accountCode: undefined,
    accountName: undefined,
    description: undefined,
    status: true,
  }
  formRef.value?.resetFields()
}

/** 获取模具列表 */
const getAccountList = async () => {
  accountList.value = []
  const data = await AccountApi.getAccountAll()
  accountList.value = data
}

/** 处理模具选择变化 */
const handleAccountChange = (accountId: number) => {
  if (!accountId) {
    formData.value.accountCode = undefined
    formData.value.accountName = undefined
    return
  }

  const selectedAccount = accountList.value?.find(account => account.id === accountId)
  if (selectedAccount) {
    formData.value.accountCode = selectedAccount.code
    formData.value.accountName = selectedAccount.name
  }
}

/** 获得模具图号BOM树 */
const getDrawingNoBomTree = async () => {
  drawingNoBomTree.value = []
  const params = {
    drawingNoId: formData.value.drawingNoId
  }
  const data = await DrawingNoBomApi.getDrawingNoBomList(params)
  const root: Tree = { id: 0, name: '顶级模具图号BOM', children: [] }
  root.children = handleTree(data, 'id', 'pid')
  drawingNoBomTree.value.push(root)
}
</script>